const { sequelize } = require('../models');

// 测试环境设置
beforeAll(async () => {
  // 连接测试数据库
  try {
    await sequelize.authenticate();
    console.log('测试数据库连接成功');
  } catch (error) {
    console.error('测试数据库连接失败:', error);
  }
});

afterAll(async () => {
  // 关闭数据库连接
  await sequelize.close();
});

// 全局测试工具
global.testUtils = {
  // 生成测试用户数据
  generateTestUser: (overrides = {}) => ({
    nickname: `测试用户${Date.now()}`,
    phone: `1${Math.floor(Math.random() * 9000000000 + 1000000000)}`,
    role: 'user',
    points: 100,
    ...overrides
  }),

  // 生成测试订单数据
  generateTestOrder: (userId, overrides = {}) => ({
    userId,
    orderNumber: `TEST${Date.now()}`,
    status: 'pending',
    totalPoints: 50,
    items: JSON.stringify([{
      productId: 1,
      productName: '测试商品',
      quantity: 1,
      pointsUsed: 50
    }]),
    ...overrides
  }),

  // 生成测试积分交易数据
  generateTestTransaction: (userId, overrides = {}) => ({
    userId,
    type: 'earn',
    amount: 10,
    source: 'test',
    description: '测试积分交易',
    balanceBefore: 100,
    balanceAfter: 110,
    ...overrides
  }),

  // 清理测试数据
  async cleanupTestData() {
    const { User, Order, PointsTransaction } = require('../models');
    
    // 删除测试数据（以TEST开头的数据）
    await PointsTransaction.destroy({
      where: { description: { [require('sequelize').Op.like]: '%测试%' } }
    });
    
    await Order.destroy({
      where: { orderNumber: { [require('sequelize').Op.like]: 'TEST%' } }
    });
    
    await User.destroy({
      where: { nickname: { [require('sequelize').Op.like]: '%测试用户%' } }
    });
  }
};

// 设置测试超时
jest.setTimeout(30000);